<!--班级管理-->
<template>
  <div class="container">
    <div class="head">
      <span class="title">班级管理</span>
      <el-button
        class="add"
        icon="el-icon-plus"
        type="primary" 
        size="small"
        round
        @click="add()"
        >新增班级</el-button
      >
    </div>

    <div class="content">
      <el-table   :data="tableData"   border v-loading="tableLoading" style="width: 100%"   stripe>
        <el-table-column
          v-for="item in columnList"
          :key="item.prop"
          :prop="item.prop"
          v-if="!teacher||item.show"
          :label="item.label"
        >
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template v-slot="{ row }">
           <el-button
           class="btn_primary"
              type="primary"
              size="small"
              icon="el-icon-edit-outline"
              @click="edit(row)"
              >编辑</el-button
            > 
            <el-popconfirm
             
              icon="el-icon-info"
              icon-color="red"
              title="是否删除班级？"
              @confirm="() => remove(row)"
            >
              <el-button
              :loading="row.removeLoading"
                slot="reference"
                type="danger"
                size="small"
                icon="el-icon-delete"
                class="delete"
                >删除</el-button
              >
              
            </el-popconfirm>
          
      
          </template>
        </el-table-column>
      </el-table>
       <el-pagination
       style="margin-top:10px"
        v-if="!teacher"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 20, 30,50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalSize">
    </el-pagination>
      <el-dialog
        :title="isAdd ? '新增' : '编辑'"
        :visible="dialogVisible"
        @update:visible="cancel"
        width="600px">
        <el-form
          :model="formData"
          ref="ruleForm"
          size="mini"
          label-width="85px"
          style="text-align:left"
        >
          <template v-for="(item, index) of columnList">
            <el-form-item
              v-if="item.edit"
              :key="index"
              :label="item.label + ':'"
              :prop="item.prop"
              :rules="item.rules ? item.rules : []"
            >
              <el-input
                v-if="item.type == 'text'"
                v-model="formData[item.prop]"
              ></el-input>
                <el-select v-else-if="item.type == 'select'"  v-model="formData[item.prop]" placeholder="请选择教师">
                <el-option
                  v-for="item in selectTeachers"
                  :key="item.userId"
                  :label="item.username"
                  :value="item.userId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </template>
        </el-form>
        <template v-slot:footer>
          <span class="dialog-footer">
            <el-button size="mini" @click="cancel() " round>取 消</el-button>
            <el-button
              :loading="submitLoading"
              size="mini"
              type="primary"
              @click="submit()"
              round
              >确 定</el-button
            >
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>

//第一行
const columnList = [
  {
    label: "班级id",
    type: "text",
    prop: "id",
    width: 120,
    //是否可以编辑，用于渲染新增编辑表单
    edit:false,
    show:true
  },
  {
    label: "班级名",
    type: "text",
    prop: "className",
    width: 120,
    rules: [{ required: true, message: "请输入班级名称", trigger: "blur" }],
    edit:true,
    show:true
  },
  {
    label: "教师id",
    type: "select",
    prop: "teacherId",
    rules: [{ required: true, message: "请选择班级教师", trigger: "blur" }],
    width: 120,
    edit:true,
    show:false
  }, {
    label: "教师用户名",
    type: "text",
    prop: "teacherName",
    width: 120,
    edit:false,
    show:false
  },

  {
    label: "学校名称",
    type: "text",
    prop: "schoolName",
    width: 120,
    edit:false,
    show:false,
  },
];
import {
  addClass,
  findByTeacherId,
  pageClassBySchool,
  updateClass,
  deleteClass,
  getUserBySchoolId,
  ClassByTeacher
} from "@/api/class";
export default {
  name: "classManage",
  data() {
    return {
       columnList,
      tableData: [       //列表数据
      ],
      dialogVisible:false, //dialog是否可见
      formData:{},
      userInfo:{},
      tableLoading:false,
      submitLoading:false,
      isAdd:true,    //是否增加
      currentPage:1,
      oldTeacherId:null, //编辑班级接口时用到旧teacherId
      pageSize:10,
      totalSize:0,
      teacher:null,
      selectTeachers:[]//添加班级时所选择的教师列表
    };
  },
  created() {
    //获取当前用户信息
    this.userInfo=JSON.parse(localStorage.getItem("user"));
    if(this.userInfo.roleName=='teacher') this.teacher=true;
     this.getTableData();
  },
  methods: {
    //获取列表
    getTableData() {
      this.tableLoading=true;
      let role = this.$store.state.role;
      if (role == "teacher") {
        this.columnList[2].edit=false;
        ClassByTeacher(this.userInfo.userId).then(res => {
          res.data.forEach(element => {
            element.removeLoading=false;
          });
          this.tableData = res.data;
        }).finally(()=>{
          this.tableLoading=false;
        });
      } else {
        this.getTeachers();
        pageClassBySchool({current:this.currentPage,limit:this.pageSize,id:this.userInfo.schoolId}).then(res => {
          res.data.forEach(element => {
            element.removeLoading=false;
          });
           this.tableData = res.data;
           this.totalSize=res.total;
        }).finally(()=>{
          this.tableLoading=false;
        });
      }
    },
    //增加班级
    add(){
        this.dialogVisible=true;
        this.isAdd=true;
    },
    //取消修改
    cancel(){
        this.formData={},
        this.dialogVisible=false;
    },
    //删除班级
    remove(row) {
      row.removeLoading=true;
        deleteClass(row.id).then(res=>{
             this.$message.success("删除成功");
        })
        .finally(()=>{
          row.removeLoading=false;
            this.getTableData();

        })
    },
    //获取教师列表
    getTeachers(){
      let obj={
        schoolId:this.userInfo.schoolId,
        role:"TEACHER",
        pageNum:1,
        pageSize:100
      }
      getUserBySchoolId(obj).then((res)=>{
        this.selectTeachers=res.data;
      }).catch(()=>{
        this.$message.error("获取教师列表失败");
      })
    },
    //编辑
    edit(data) {
        this.formData={...data};
        this.oldTeacherId=data.teacherId;
        this.isAdd=false;
        this.dialogVisible=true;
    },
    //确定后提交
    submit(){
       this.$refs.ruleForm.validate((valid) => {
            if (valid) {
                this.submitLoading = true;
                if (this.isAdd) {
                 this.formData.schoolId=this.userInfo.schoolId;
                 if(!this.formData.teacherId){
                   this.formData.teacherId=this.userInfo.userId;
                 }
                addClass(this.formData)
                  .then((res) => {
                    console.log(res);
                    this.$message.success("新增成功");
                    this.getTableData();
                  })
                  .finally(() => {
                    this.submitLoading = false;
                    this.cancel();
                  });
              } else {
                delete this.formData.createdTime;
                delete this.formData.updatedTime;
                delete this.formData.removeLoading;
                delete this.formData.schoolName;
                delete this.formData.teacherName;
                this.formData.oldTeacherId=this.oldTeacherId;
                updateClass(this.formData)
                  .then((res) => {
                    console.log(res);
                    this.$message.success("修改成功");
                    this.getTableData();
                  })
                  .finally(() => {
                    this.submitLoading = false;
                    this.cancel();
                  });
                }
          }
            })
        
    },
    //页面大小
    handleSizeChange(size){
      this.pageSize=size;
      this.getTableData();
    },
    //分页
    handleCurrentChange(page){
      this.currentPage=page;
      this.getTableData();
    },
  }
};
</script>

<style scoped>
.el-dialog 
 {
     
      background-color:red;
}
.title {
  font-size: 30px;
  color: #409eff;
  margin-bottom: 30px;
  font-weight: bold;
}
.content {
  margin-top: 20px;
}
.add {
  position: absolute;
  right: 100px;
  background-color:#5b8bff;
  border-color:#5b8bff;
  display: inline-block;
  font-size: 15px;
  cursor: pointer;
}
.delete{
   color:red;
   margin-left:30px;
}
.container .el-dialog__footer{
    position:relative;
}
.container .el-dialog__footer .dialog-footer{
   position:absolute;
   left:50%;
   transform:translate(-50%,-65%);
}
 el-popconfirm{
  background-color: tomato !important;
}
</style>
